package com.ava.avamedia.lottery;

import java.io.IOException;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.ava.avamedia.R;
import com.ava.avamedia.adapter.CityAdapter;
import com.ava.avamedia.model.Cities;
import com.ava.avamedia.util.Constants;
import com.congnt.library.utility.DialogUtils;
import com.congnt.library.utility.HTTPClientUtil;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ListCitiesActivity extends Activity {
	public String[] MIEN_TRUNG = { "Bình Định", "Đà Nẵng", "Đắk Lắk",
			"Đắk Nông", "Gia Lai", "Huế", "Khánh Hòa", "Kon Tum", "Ninh Thuận",
			"Phú Yên", "Quảng Bình", "Quảng Nam", "Quảng Ngãi", "Quảng Trị" };
	public String[] MIEN_NAM = { "An Giang", "Bạc Liêu", "Bến Tre",
			"Bình Dương", "Bình Phước", "Bình Thuận", "Cà Mau", "Cần Thơ",
			"Đà Lạt", "Đồng Nai", "Đồng Tháp", "Hậu Giang", "Kiên Giang",
			"Long An", "Sóc Trăng", "Tây Ninh", "Tiền Giang", "TP.HCM",
			"Trà Vinh", "Vĩnh Long", "Vũng Tàu" };
	private int region;
	private ListView listView;
	public ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		region = getIntent().getIntExtra(Constants.REGION, 0);
		setContentView(R.layout.activity_region);
		listView = (ListView) findViewById(R.id.activity_region_list_view);
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Cities city = (Cities) arg0.getAdapter().getItem(arg2);
				openMenuActivity(city);
			}
		});
		if (HTTPClientUtil.isInternetConection()) {
			new LoadCitiesAsync().execute();
		}else{
			DialogUtils.showAlertDialog(this, "Error", "Không có kết nối Internet");
		}
	}
	public void openMenuActivity(Cities city){
		Intent intent =new Intent();
		intent.setClass(ListCitiesActivity.this, MenuActivity.class);
		intent.putExtra(Constants.REGION, region);
		intent.putExtra(Constants.URL_RESULT, city.url);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(intent);
	}
	public void initListView(ArrayList<Cities> array) {
		CityAdapter adapter = new CityAdapter(this, array);
		listView.setAdapter(adapter);
	}

	private static final String TAG = ListCitiesActivity.class.getSimpleName();

	class LoadCitiesAsync extends AsyncTask<Void, Void, ArrayList<Cities>> {

		@Override
		protected ArrayList<Cities> doInBackground(Void... params) {
			Document doc;
			try {
				doc = Jsoup.connect(Constants.URL_KQ)
						.userAgent(Constants.USER_AGENT).get();
				Elements elementRoot = doc
						.body()
						.select("form#aspnetForm > div.bg_body > div.mn_left > div.main_contain > table > tbody > *");
				return getAllCitiesByRootElement(elementRoot);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = DialogUtils
					.showProgress(
							ListCitiesActivity.this,
							"Đang lấy danh sách các tỉnh mở thưởng hôm nay tại trang web http://ketquaday.vn.....");
		}

		@Override
		protected void onPostExecute(ArrayList<Cities> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			initListView(result);
		}

	}

	public ArrayList<Cities> getAllCitiesByRootElement(Elements root) {
		ArrayList<Cities> arrayList = null;
		switch (region) {
		case 1:
			arrayList = new ArrayList<Cities>();
			for (Element element : root) {
				String name = element.child(0).select("a").text();
				String url = element.child(0).select("a").attr("href");
				for (int i = 0; i < MIEN_TRUNG.length; i++) {
					if (name.contains(MIEN_TRUNG[i])) {
						Cities city = new Cities();
						city.name = name;
						city.url = url;
						arrayList.add(city);
					}
				}
			}
			break;
		case 2:
			arrayList = new ArrayList<Cities>();
			for (Element element : root) {
				String name = element.child(0).select("a").text();
				String url = element.child(0).select("a").attr("href");
				for (int i = 0; i < MIEN_NAM.length; i++) {
					if (name.contains(MIEN_NAM[i])) {
						Cities city = new Cities();
						city.name = name;
						city.url = url;
						arrayList.add(city);
					}
				}
			}
			break;
		default:
			break;
		}
		return arrayList;
	}
}
